import requests
import pygal
from pygal.style import LightColorizedStyle, LightenStyle

# 执行api调用并存储响应
# 查询github的python项目，按星级排序返回
url = 'https://api.github.com/search/repositories?q=language:python&sort=stars'
r = requests.get(url)
print("Status Code:", r.status_code)

# 将API响应存储在一个变量中
# 用方法json() 将这些信息转换为一个Python 字典
response_dict = r.json()
# 处理结果
repo_dicts = response_dict['items']
# print("Repositories returned:", len(repo_dicts))
# # 第一个仓库
# repo_dict = repo_dicts[0]
# print("\nSelected information about first repository:")
# print('Name:', repo_dict['name'])  # 项目名称
# print('Owner:', repo_dict['owner']['login'])  # 所有者和所有者登陆名
# print('Stars:', repo_dict['stargazers_count'])  # 星级
# print('Repository:', repo_dict['html_url'])  # 地址
# print('Created:', repo_dict['created_at'])  # 创建时间
# print('Updated:', repo_dict['updated_at'])  # 最后一次更新时间
# print('Description:', repo_dict['description'])  # 描述

names, plot_dicts = [], []
for repo_dict in repo_dicts:
    names.append(repo_dict['name'])
    plot_dict = {'value': repo_dict['stargazers_count'],
                 # 'label': repo_dict['description'],
                 'xlink': repo_dict['html_url']
                 }
    plot_dicts.append(plot_dict)

# 可视化 柱状图
my_style = LightenStyle('#333366', base_style=LightColorizedStyle)

my_config = pygal.Config()
my_config.x_label_rotation = 45
my_config.show_legend = False
my_config.title_font_size = 24
my_config.label_font_size = 14
my_config.major_label_font_size = 18
my_config.truncate_label = 15
my_config.show_y_guides = False
my_config.width = 1000

chart = pygal.Bar(my_config, my_style=my_style)
chart.title = 'Most-Starred Python Projects on Github'
chart.x_labels = names
chart.add('', plot_dicts)
chart.render_to_file('python_repos.svg')
